/**
 * 品牌页入库数量图表组件
 */
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRoute } from 'vue-router'
import * as echarts from 'echarts'
import http from '@/axios/http'
import adaptivePx from '@/utils/adaptivePx'

const route = useRoute()
const brand = ref(route.query.brand)

const main = ref()
const quantityChart = ref()
const quantityDetail = ref()
let myChart = null

const date = new Date()
const lastYear = (date.getFullYear() - 1) + '年'
const thisYear = date.getFullYear() + '年'

async function getQuantityChart() {
  await http.post('/brand/getQuantityChart', {
    brand: brand.value
  }).then(res => {
    quantityChart.value = res.data
  }).catch(err => {
    console.log(err)
  })
}

async function getQuantityDetail() {
  await http.post('/brand/getQuantityDetail', {
    brand: brand.value
  }).then(res => {
    quantityDetail.value = res.data
  }).catch(err => {
    console.log(err)
  })
}

function init() {
  myChart = echarts.init(main.value, null, { renderer: 'svg'})

  let option = {
    title: {
      text: '入库数量',
      textStyle: {
        color: 'white',
        fontSize: adaptivePx(16),
        fontWeight: 'normal'
      },
      left: '2%',
      top: '2%'
    },
    color: ['#1e90ff', '#2fa8c3'],
    legend: {
      textStyle: {
        color: 'white',
        fontSize: adaptivePx(14),
        fontWeight: 'normal'
      },
      top: '2%',
      right: '2%',
      data: [lastYear, thisYear]
    },
    grid: {
      left: '3%',
      top: '27%',
      right: '5%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      axisLabel: {
        color: 'white',
        fontSize: adaptivePx(12),
        fontWeight: 'normal'
      },
      data: quantityChart.value.month
    },
    yAxis: {
      axisLabel: {
        color: 'white',
        fontSize: adaptivePx(12),
        fontWeight: 'normal'
      },
      axisLine: {
        lineStyle: {
          type: 'solid'
        },
        show: true
      },
      splitLine: {
        lineStyle: {
          type: 'dashed',
          color: '#666'
        },
        show: true
      }
    },
    series: [
      {
        name: lastYear,
        type: 'bar',
        data: quantityChart.value.lastQuantityChart,
        markPoint: {
          symbol: quantityChart.value.lastQuantityChart[quantityChart.value.lastQuantityChart.length - 1] > 0 ? 'pin' : 'none',
          symbolSize: adaptivePx(60),
          label: {
            color: 'white',
            fontSize: adaptivePx(12),
            fontWeight: 'normal'
          },
          data: [
            {
              name: 'Total',
              coord: [quantityChart.value.lastQuantityChart.length - 1, quantityChart.value.lastQuantityChart[quantityChart.value.lastQuantityChart.length - 1]],
              value: quantityChart.value.lastQuantityChart[quantityChart.value.lastQuantityChart.length - 1] > 1000 ? Math.round(quantityChart.value.lastQuantityChart[quantityChart.value.lastQuantityChart.length - 1] / 1000) + 'k' : quantityChart.value.lastQuantityChart[quantityChart.value.lastQuantityChart.length - 1]
            }
          ]
        },
        barWidth: '15%'
      },
      {
        name: thisYear,
        type: 'bar',
        data: quantityChart.value.thisQuantityChart,
        markPoint: {
          symbol: quantityChart.value.thisQuantityChart[quantityChart.value.thisQuantityChart.length - 1] > 0 ? 'pin' : 'none',
          symbolSize: adaptivePx(60),
          label: {
            color: 'white',
            fontSize: adaptivePx(12),
            fontWeight: 'normal'
          },
          data: [
            {
              name: 'Total',
              coord: [quantityChart.value.thisQuantityChart.length - 1, quantityChart.value.thisQuantityChart[quantityChart.value.thisQuantityChart.length - 1]],
              value: quantityChart.value.thisQuantityChart[quantityChart.value.thisQuantityChart.length - 1] > 1000 ? Math.round(quantityChart.value.thisQuantityChart[quantityChart.value.thisQuantityChart.length - 1] / 1000) + 'k' : quantityChart.value.thisQuantityChart[quantityChart.value.thisQuantityChart.length - 1]
            }
          ]
        },
        barWidth: '15%'
      }
    ],
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        axis: 'x',
      },
      textStyle: {
        color: 'black',
        fontSize: adaptivePx(14),
        fontWeight: 'normal'
      },
      backgroundColor: 'rgba(171, 182, 212, 0.9)',
      borderWidth: 0,
      position: function (point, params, dom, rect, size) {
        return [point[0] - size.contentSize[0] - adaptivePx(20), point[1] - size.contentSize[1] * 0.5]
      },
      formatter: function (params) {
        let year = (new Date()).getFullYear()
        let month = quantityDetail.value[params[0].name]
        let content = ''

        let hasThis = false
        let hasLast = false

        let thisTotal = 0
        let lastTotal = 0

        if (!month || month.length === 0) {
          return "暂无数据"
        }

        content += `
          <table style="text-align: center; font-weight: normal;">
            <thead>
              <tr>
                <th></th>
        `

        for (let item of month) {
          if (item.in_qty1) {
            hasThis = true
          }
          if (item.in_qty2) {
            hasLast = true
          }
        }

        if (hasThis) {
          content += `
                <th>&nbsp;${ year }年${ params[0].name === 'Total' ? '全年' : params[0].name + '月' }&nbsp;</th>
          `
        }

        if (hasLast) {
          content += `
                <th>&nbsp;${ year - 1 }年${ params[0].name === 'Total' ? '全年' : params[0].name + '月' }&nbsp;</th>
          `
        }

        if (hasThis && hasLast) {
          content += `
                <th>&nbsp;VS${ String(year - 1).substring(2) }&nbsp;</th>
          `
        }

        content += `
              </tr>
            </thead>
            <tbody>
        `

        for (let item of month) {
          thisTotal += item.in_qty1
          lastTotal += item.in_qty2

          content += `
            <tr>
              <td style="text-align: left;">${ item.factory }</td>
          `
          if (hasThis) {
            content +=  `
              <td>${ item.in_qty1.toLocaleString() }</td>
            `
          }
          if (hasLast) {
            content +=  `
              <td>${ item.in_qty2.toLocaleString() }</td>
            `
          }
          if (hasThis && hasLast) {
            let diff = item.in_qty1 - item.in_qty2
            if (diff > 0) {
              content += `
                <td style="color: blue;">+${ diff.toLocaleString() }</td>
              `
            } else {
              content += `
                <td style="color: red;">${ diff.toLocaleString() }</td>
              `
            }
          }
          content += `
              </tr>
          `
        }

        if (month.length > 1) {
          content += `
              <tr>
                <td style="text-align: left;">合计</td>
          `
          if (hasThis) {
            content +=  `
              <td>${ thisTotal.toLocaleString() }</td>
            `
          }
          if (hasLast) {
            content +=  `
              <td>${ lastTotal.toLocaleString() }</td>
            `
          }
          if (hasThis && hasLast) {
            let diff = thisTotal - lastTotal
            if (diff > 0) {
              content += `
                <td style="color: blue;">+${ diff.toLocaleString() }</td>
              `
            } else {
              content += `
                <td style="color: red;">${ diff.toLocaleString() }</td>
              `
            }
          }
        }
        content += `
              </tr>
        `

        content += `
            </tbody>
          </table>
        `

        return content
      }
    }
  }

  myChart.setOption(option)
}

function myChartResize() {
  if (myChart) {
    myChart.resize()
  }
}

onMounted(async () => {
  await getQuantityChart()
  await getQuantityDetail()
  init()
  
  window.addEventListener('resize', myChartResize)
})

onUnmounted(() => {
  window.removeEventListener('resize', myChartResize)
})
</script>

<template>
  <div id="brand-quantity-chart" ref="main"></div>
</template>

<style lang="scss" scoped>
#brand-quantity-chart {
  width: 100%;
  height: 100%;
}
</style>